<script setup>
import { nextTick, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { Message } from "@arco-design/web-vue";
import planApi from "@/api/planApi";
import summaryApi from "@/api/summaryApi";
import constants from "@/utils/constants";
import Upload from "@/components/Upload.vue";
import dayjs from "dayjs";

const router = useRouter();

const submitForm = ref();
const searchForm = ref();
const historyParams = history.state.params;
const searchModel = reactive({
  planId: historyParams.planId,
  downloadGradeId: 16,
  exportType: "1",
  scoreType: "1",
  exportTimeType: 'origin'
});
const visible = ref(false);
const uploadVisible = ref(false);
const loading = ref(false);
const downloading = ref(false);

let uploadData = ref({
  planId: historyParams.planId,
});
let schoolList = ref([]);
let gradeClassesList = ref([]);
let classesList = ref([]);

const exportVisiable = ref(false);

let pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 15,
  showPageSize: true,
  pageSizeOptions: [15, 25, 30, 50],
  showTotal: true,
  pageChange: (current) => {
    pagination.current = current;
    search();
  },
  pageSizeChange(size) {
    pagination.pageSize = size;
    search();
  },
});

const examProjectColumns = ref([
  {
    title: "学校名称",
    dataIndex: "schoolName",
    width: 180,
    fixed: "left",
  },
  {
    title: "学生姓名",
    dataIndex: "name",
    width: 100,
    fixed: "left",
  },
  {
    title: "学籍号",
    dataIndex: "studyCode",
    width: 200,
    fixed: "left",
  },
  {
    title: "年级",
    dataIndex: "gradeId",
    width: 70,
    fixed: "left",
  },
  {
    title: "班级",
    dataIndex: "classesName",
    width: 100,
    fixed: "left",
  },
])

let highSchoolColumns = [
  {
    title: "学校名称",
    dataIndex: "schoolName",
    width: 180,
    fixed: "left",
  },
  {
    title: "学生姓名",
    dataIndex: "name",
    width: 100,
    fixed: "left",
  },
  {
    title: "学籍号",
    dataIndex: "studyCode",
    width: 200,
    fixed: "left",
  },
  {
    title: "年级",
    dataIndex: "gradeId",
    width: 70,
    fixed: "left",
  },
  {
    title: "班级",
    dataIndex: "classesName",
    width: 100,
    fixed: "left",
  },
  {
    title: "身高",
    dataIndex: "heightResult",
    width: 100,
  },
  {
    title: "体重",
    dataIndex: "weightResult",
    width: 100,
  },
  {
    title: "BMI",
    dataIndex: "bmiResult",
    width: 100,
  },
  {
    title: "分数",
    dataIndex: "bmiScore",
    width: 100,
  },
  {
    title: "等级",
    dataIndex: "bmiLevel",
    width: 100,
  },
  {
    title: "肺活量",
    dataIndex: "vitalResult",
    width: 100,
  },
  {
    title: "分数",
    dataIndex: "vitalScore",
    width: 100,
  },
  {
    title: "等级",
    dataIndex: "vitalLevel",
    width: 100,
  },
  {
    title: "50米跑",
    dataIndex: "run50Result",
    width: 120,
  },
  {
    title: "分数",
    dataIndex: "run50Score",
    width: 100,
  },
  {
    title: "等级",
    dataIndex: "run50Level",
    width: 100,
  },
  {
    title: "坐位体前屈",
    dataIndex: "sitAndReachResult",
    width: 120,
  },
  {
    title: "分数",
    dataIndex: "sitAndReachScore",
    width: 100,
  },
  {
    title: "等级",
    dataIndex: "sitAndReachLevel",
    width: 100,
  },
  {
    title: "一分钟仰卧起坐",
    dataIndex: "abdominalResult",
    width: 150,
  },
  {
    title: "分数",
    dataIndex: "abdominalScore",
    width: 100,
  },
  {
    title: "附加分",
    dataIndex: "abdominalExtraScore",
    width: 100,
  },
  {
    title: "等级",
    dataIndex: "abdominalLevel",
    width: 100,
  },
  {
    title: "立定跳远",
    dataIndex: "jumpResult",
    width: 120,
  },
  {
    title: "分数",
    dataIndex: "jumpScore",
    width: 100,
  },
  {
    title: "等级",
    dataIndex: "jumpLevel",
    width: 100,
  },
  {
    title: "引体向上",
    dataIndex: "pullUpResult",
    width: 120,
  },
  {
    title: "分数",
    dataIndex: "pullUpScore",
    width: 100,
  },
  {
    title: "附加分",
    dataIndex: "pullUpExtraScore",
    width: 100,
  },
  {
    title: "等级",
    dataIndex: "pullUpLevel",
    width: 100,
  },
  {
    title: "1000米跑",
    dataIndex: "run1000Result",
    width: 120,
  },
  {
    title: "分数",
    dataIndex: "run1000Score",
    width: 100,
  },
  {
    title: "附加分",
    dataIndex: "run1000ExtraScore",
    width: 100,
  },
  {
    title: "等级",
    dataIndex: "run1000Level",
    width: 100,
  },
  {
    title: "800米跑",
    dataIndex: "run800Result",
    width: 120,
  },
  {
    title: "分数",
    dataIndex: "run800Score",
    width: 100,
  },
  {
    title: "附加分",
    dataIndex: "run800ExtraScore",
    width: 100,
  },
  {
    title: "等级",
    dataIndex: "run800Level",
  },
  {
    title: "总分",
    fixed: "right",
    width: 100,
    dataIndex: "totalScore",
  },
];

let finalColumns = ref([]);

let columns = [
  {
    title: "学校名称",
    dataIndex: "schoolName",
    width: 180,
    fixed: "left",
  },
  {
    title: "学生姓名",
    dataIndex: "name",
    width: 100,
    fixed: "left",
  },
  {
    title: "学籍号",
    dataIndex: "studyCode",
    width: 200,
    fixed: "left",
  },
  {
    title: "年级",
    dataIndex: "gradeId",
    width: 70,
    fixed: "left",
  },
  {
    title: "班级",
    dataIndex: "classesName",
    width: 100,
    fixed: "left",
  },
  {
    title: "身高",
    dataIndex: "heightResult",
    width: 100,
  },
  {
    title: "体重",
    dataIndex: "weightResult",
    width: 100,
  },
  {
    title: "BMI",
    dataIndex: "bmiResult",
    width: 100,
  },
  {
    title: "分数",
    dataIndex: "bmiScore",
    width: 100,
  },
  {
    title: "等级",
    dataIndex: "bmiLevel",
    width: 100,
  },
  {
    title: "肺活量",
    dataIndex: "vitalResult",
    width: 100,
  },
  {
    title: "分数",
    dataIndex: "vitalScore",
    width: 100,
  },
  {
    title: "等级",
    dataIndex: "vitalLevel",
    width: 100,
  },
  {
    title: "50米跑",
    dataIndex: "run50Result",
    width: 120,
  },
  {
    title: "分数",
    dataIndex: "run50Score",
    width: 100,
  },
  {
    title: "等级",
    dataIndex: "run50Level",
    width: 100,
  },
  {
    title: "坐位体前屈",
    dataIndex: "sitAndReachResult",
    width: 120,
  },
  {
    title: "分数",
    dataIndex: "sitAndReachScore",
    width: 100,
  },
  {
    title: "等级",
    dataIndex: "sitAndReachLevel",
    width: 100,
  },
  {
    title: "一分钟跳绳",
    dataIndex: "ropeSkipResult",
    width: 120,
  },
  {
    title: "分数",
    dataIndex: "ropeSkipScore",
    width: 100,
  },
  {
    title: "等级",
    dataIndex: "ropeSkipLevel",
    width: 100,
  },
  {
    title: "一分钟仰卧起坐",
    dataIndex: "abdominalResult",
    width: 150,
  },
  {
    title: "分数",
    dataIndex: "abdominalScore",
    width: 100,
  },
  {
    title: "等级",
    dataIndex: "abdominalLevel",
    width: 100,
  },
  {
    title: "50米x8往返跑",
    dataIndex: "run50x8Result",
    width: 130,
  },
  {
    title: "分数",
    dataIndex: "run50x8Score",
    width: 100,
  },
  {
    title: "等级",
    dataIndex: "run50x8Level",
  },
  {
    title: "总分",
    fixed: "right",
    width: 100,
    dataIndex: "totalScore",
  }
];

const data = ref([]);

const highScroll = {
  x: 4200,
  y: 600,
};

const scroll = {
  x: 3200,
  y: 600,
};

const queryPlanProjectList = () => {
  planApi.queryProjectList({
    planId: historyParams.planId
  }).then(res => {
    console.log(res);
    if (res && res.length > 0) {
      res.forEach(project => {
        examProjectColumns.value.push({
          dataIndex: project,
          title: project,
          width: 120
        })
        if (project != '身高' && project != '体重') {
          examProjectColumns.value.push({
            dataIndex: project + '得分',
            title: '得分',
            width: 120
          })
        }
      })
      examProjectColumns.value.push({
        dataIndex: 'totalScore',
        title: '总分',
        fixed: "right",
        width: 90
      })
      examProjectColumns.value.push({
        title: "等级",
        fixed: "right",
        width: 100,
        dataIndex: "totalLevel",
      },)

    }
  })
}

const showAddDialog = () => {
  visible.value = true;
  submitForm.value.resetFields();
  submitData.value = {
    schoolId: historyParams.schoolId,
    sex: "1",
  };
};

const openExportVisiable = () => {
  exportVisiable.value = true;
}

const downloadExcel = () => {
  downloading.value = true;
  summaryApi.exportSummary(searchModel).then((res) => {
    const content = res.data;
    const blob = new Blob([content], { type: "application/octet-stream" });
    let suixx = searchModel.exportType == 1 ? ".xlsx" : ".zip";
    const fileName =
      "评分等级汇总-" + dayjs().format("YYYYMMDDHHmmss") + suixx;

    if (typeof window.navigator.msSaveBlob !== "undefined") {
      window.navigator.msSaveBlob(blob, fileName);
    } else {
      const fileUrl = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = fileUrl;
      a.target = "_blank";
      a.download = fileName;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
    downloading.value = false;
  });
};

const closeUploadDialog = () => {
  uploadVisible.value = false;
  refresh();
};

const schoolSelectChange = (schoolId) => {
  if (schoolId) {
    planApi
      .getGradeClassesList({
        planId: historyParams.planId,
        schoolId: schoolId,
      })
      .then((res) => {
        gradeClassesList.value = res;
      });
  } else {
    gradeClassesList.value = [];
    classesList.value = [];
    searchModel.classesId = "";
    searchModel.gradeId = "";
  }
};

const changeSelectDownloadGrade = (gradeId) => {
  if (gradeId <= 16) {
    finalColumns.value = Object.assign([], columns);
  } else {
    finalColumns.value = Object.assign([], highSchoolColumns);
  }
  refresh();
};

const changeSelectGrade = (gradeId) => {
  let gradeModel = gradeClassesList.value.find((grade) => {
    return grade.id == gradeId;
  });
  if (gradeModel && gradeModel.children && gradeModel.children.length > 0) {
    classesList.value = gradeModel.children;
    if (gradeId <= 16) {
      searchModel.downloadGradeId = 16;
      finalColumns.value = Object.assign([], columns);
    } else {
      searchModel.downloadGradeId = 21;
      finalColumns.value = Object.assign([], highSchoolColumns);
    }
  } else {
    searchModel.classesId = "";
    classesList.value = [];
  }
};

const deleteRecord = (record) => {
  summaryApi
    .delete({
      id: record.id,
    })
    .then((res) => {
      refresh();
    });
};

const schoolTypes = ref([]);

const getSchoolList = () => {
  planApi
    .getSchoolList({
      planId: historyParams.planId,
    })
    .then((res) => {
      schoolList.value = res;
      res.forEach((element) => {
        if (element.schoolType.indexOf("1") != -1) {
          schoolTypes.value.push(16);
        }
        if (
          element.schoolType.indexOf("2") != -1 ||
          element.schoolType.indexOf("3") != -1 ||
          element.schoolType.indexOf("4") != -1
        ) {
          schoolTypes.value.push(21);
        }
      });
      if (schoolTypes.value.length >= 1) {
        searchModel.downloadGradeId = schoolTypes.value[0];
      }
      search();
    });
};

const search = (current = 1, size = 15) => {
  var params = {
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
    queryParam: Object.assign({}, searchModel),
  };
  loading.value = true;
  summaryApi.page(params).then((res) => {
    let records = res.records;
    records.forEach(rec => {

      if (rec.testResultList && rec.testResultList.length > 0) {

        rec.testResultList.forEach(item => {
          rec[item.prjName] = !item.result ? item.resultType : item.result;
          if (item.prjName != '身高' && item.prjName != '体重') {
            rec[item.prjName + '得分'] = !item.score ? '-' : item.score;
          }

        })
      }
    })
    data.value = records;
    pagination.total = res.total;
    loading.value = false;
  });
};

const refresh = () => {
  search();
};

const getNationName = (value) => {
  let nationItem = constants.nationList.find((res) => {
    return res.value == value;
  });
  return !nationItem ? "" : nationItem.label;
};

const reset = () => {
  searchForm.value.resetFields();
  searchModel.classesId = "";
  searchModel.gradeId = "";
  gradeClassesList.value = [];
  classesList.value = [];
};
finalColumns = Object.assign([], highSchoolColumns);
getSchoolList();

queryPlanProjectList();
</script>

<template>
  <div class="main-con">
    <div style="padding-bottom: 16px">
      <a-breadcrumb>
        <a-breadcrumb-item>首页</a-breadcrumb-item>
        <a-breadcrumb-item>体测管理</a-breadcrumb-item>
        <a-breadcrumb-item>成绩汇总查询</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <a-card>
      <a-row>
        <a-col :flex="1">
          <a-form ref="searchForm" :model="searchModel" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }"
            label-align="left">
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-item field="schoolId" label="学校">
                  <a-select v-model="searchModel.schoolId" placeholder="请选择学校" allow-clear @change="schoolSelectChange">
                    <a-option v-for="school in schoolList" :value="school.id" :key="school.id"
                      :label="school.name"></a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="gradeId" label="年级/班级">
                  <a-space>
                    <a-select style="width: 120px" v-model="searchModel.gradeId" @change="changeSelectGrade"
                      placeholder="年级">
                      <a-option value="">全部</a-option>
                      <a-option v-for="item in gradeClassesList" :key="item.id" :value="item.id">{{ item.name
                        }}</a-option>
                    </a-select>
                    <a-select style="width: 120px" v-model="searchModel.classesId" placeholder="班级">
                      <a-option value="">全部</a-option>
                      <a-option v-for="classes in classesList" :key="classes.id" :value="classes.id">{{ classes.name
                        }}</a-option>
                    </a-select>
                  </a-space>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="name" label="学生姓名">
                  <a-input v-model="searchModel.name" placeholder="请输入姓名" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item field="sex" label="性别">
                  <a-select v-model="searchModel.sex" placeholder="请选择性别">
                    <a-option value="">全部</a-option>
                    <a-option value="1">男</a-option>
                    <a-option value="2">女</a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="studyCode" label="学籍号">
                  <a-input v-model="searchModel.studyCode" placeholder="请输入学籍号" />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item field="testQueryDate" label="测试时间">
                  <a-date-picker v-model="searchModel.testQueryDate" :style="{ width: '100%' }" />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="search()">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="reset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </a-card>

    <a-card style="margin-top: 20px" title="成绩汇总列表">
      <template #extra>
        <a-space size="large">
          <a-radio-group type="button" @change="changeSelectDownloadGrade" v-model="searchModel.downloadGradeId">
            <a-radio :value="16" v-if="schoolTypes.includes(16)">小学</a-radio>
            <a-radio :value="21" v-if="schoolTypes.includes(21)">初高中大学</a-radio>
          </a-radio-group>
          <a-button :loading="downloading" type="primary" @click="openExportVisiable">
            <template #icon>
              <icon-download />
            </template>
            {{ downloading ? '正在导出...' : '导出成绩汇总' }}
          </a-button>
        </a-space>
      </template>
      <div class="toolbar flex flex-v-center">
        <a-space> </a-space>
        <div style="clear: both"></div>
      </div>
      <a-table v-if="searchModel.downloadGradeId == 16" :columns="examProjectColumns" row-key="id" :scroll="scroll"
        :loading="loading" :data="data" @page-change="pagination.pageChange"
        @page-size-change="pagination.pageSizeChange" :pagination="pagination" :bordered="false">
        <template #nation="{ record }">
          {{ getNationName(record.nation) }}
        </template>
        <template #sex="{ record }">
          {{ record.sex == "1" ? "男" : " 女" }}
        </template>
      </a-table>
      <a-table v-if="searchModel.downloadGradeId == 21" :columns="examProjectColumns" row-key="id" :scroll="highScroll"
        :loading="loading" :data="data" @page-change="pagination.pageChange"
        @page-size-change="pagination.pageSizeChange" :pagination="pagination" :bordered="false">
        <template #nation="{ record }">
          {{ getNationName(record.nation) }}
        </template>
        <template #sex="{ record }">
          {{ record.sex == "1" ? "男" : " 女" }}
        </template>
      </a-table>
    </a-card>
  </div>

  <a-modal v-model:visible="exportVisiable" @ok="downloadExcel">
    <template #title>
      导出成绩汇总
    </template>
    <a-form :model="searchModel">
      <a-form-item label="分数类型">
        <a-radio-group v-model="searchModel.scoreType">
          <a-radio value="1">按权重</a-radio>
          <a-radio value="2">原分数</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="导出类型">
        <a-radio-group v-model="searchModel.exportType">
          <a-radio value="1">全部</a-radio>
          <a-radio value="2">按学校分组</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="时间格式">
        <a-radio-group v-model="searchModel.exportTimeType">
          <a-radio value="origin">原始成绩</a-radio>
          <a-radio value="minutes">非零进一</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal v-model:visible="uploadVisible" title="导入测试成绩数据" hide-cancel width="600px" @ok="closeUploadDialog">
    <a-space direction="vertical" style="width: 100%; text-align: center">
      <div style="color: #999">
        暂时只支持符合导入模板要求的文件进行上传，请按需下载导入模板，编辑后再上传
      </div>
      <a-button type="link" href="/成绩上传模板.xlsx" style="margin-bottom: 10px">导入成绩模板下载</a-button>
      <Upload :uploadData="uploadData" :draggable="true" action="/admin/v1/testResult/importTestData" />
    </a-space>
  </a-modal>
</template>

<style scoped></style>
